package com.zxt.content.user.utils;

import com.zxt.content.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author zxt
 */
@Component
public class RedisUtils {

    private static RedisTemplate redisTemplate;

    private static String REDIS_PREFIX = "content:";

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtils.redisTemplate = redisTemplate;
    }

    public static Object get(String key) {
        return StringUtils.isEmpty(key) ? null : redisTemplate.opsForValue().get(getRealKey(key));
    }

    private static String getRealKey(String key) {
        return REDIS_PREFIX + "-" + key;
    }

    public static void set(String key, Object value, TimeUnit unit, long timeout) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.opsForValue().set(key, value, timeout, unit);
        }
    }

    public static void expire(String key, TimeUnit unit, long timeout) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.expire(key, timeout, unit);
        }
    }

    public static void delete(String key) {
        if (!StringUtils.isEmpty(key)) {
            key = getRealKey(key);
            redisTemplate.delete(key);
        }
    }
}
